package one.stand.controller.index;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.dto.FollowCountResponse;
import com.jmp.api.dto.FollowResponse;
import com.jmp.api.dto.FollowUserResponse;
import com.jmp.api.util.LabelUtil;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.ArticleApi;
import com.jmp.base.DynamicApi;
import com.jmp.base.UserApi;
import com.jmp.base.dto.*;
import com.jmp.feign.DynamicFeign;
import com.jmp.feign.LiveFeign;
import com.jmp.feign.UserFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.*;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.*;
import one.stand.model.*;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.GoodsPhotoService;
import one.stand.service.RecordPublicService;
import one.stand.service.sys.ArticleTypeService;
import one.stand.service.sys.SysDictValueService;
import one.stand.service.sys.UserContentService;
import one.stand.service.user.UserAdminService;
import one.stand.util.*;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "首页关注")
@RestController
@RequestMapping("/follow")
public class FollowController {
    @Autowired
    private LiveFeign liveFeign;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private DynamicFeign dynamicFeign;

    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private DynamicMapperExt dynamicMapperExt;
    @Autowired
    private ArticleMapperExt articleMapperExt;
    @Autowired
    private ArticleTypeService articleTypeService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private SysDictValueService sysDictValueService;

    @Autowired
    private UserApiCrmAppMapper userApiCrmAppMapper;
    @Autowired
    private GoodsApiCrmAppMapper goodsApiCrmAppMapper;
    @Autowired
    private ArticleApiCrmAppMapper articleApiCrmAppMapper;

    @ApiOperation(value = "1列表; 已废弃;使用/follow/user")
    @GetMapping("")
    @SecurityAuthCheck
    @Deprecated
    public ResultModel<FollowResponse> indexNew(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        if (request.getPageNum() == 1) {
            userFeign.viewSave(UserViewSaveDto.builder().userId(optUser.getUserId()).type(UserApi.VIEW_TYPE_FOLLOW).build());
        }

        boolean openLive = RequestContextHolder.getRequestContext().isIos() && sysDictValueService.isOn(SysDictValueService.Type.LIVE_OPEN, "APP");

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<FollowResponse.Company> companyList = userApiCrmAppMapper.selectFollow(optUser.getUserId(), RecordPublicService.ITEMTYPE_COMPANY, null);
        PageResponse2<FollowResponse.Company> companyPageResponse2 = ConvertUtils.page2(companyList, company -> {

            Company2Dto companyModel = companyBaseService.get2(company.getCompanyId());
            boolean hasZkgx = companyBaseService.hasZkgx(companyModel.getCompanyId());
            company.setCompanyName(companyModel.getCompanyName());
            company.setCompanyLogo(companyModel.getCompanyLogo());
            company.setCompanyLevel(companyModel.countCompanyLevelView());
            company.setHasZkgx(BooleanUtils.toInteger(hasZkgx));

            if (company.getType() == 1) {
                Dynamic dynamic = dynamicMapperExt.selectByPrimaryKey(company.getItemId());
                if (Objects.isNull(dynamic)) {
                    return null;
                }
                company.setDynamic(FollowResponse.Dynamic.builder()
                        .dynamicId(dynamic.getDynamicId())
                        .photos(dynamic.getPhotos())
                        .title(dynamic.getTitle())
                        .type(dynamic.getType())
                        .build());
            } else if (company.getType() == 2) {
                Article article = articleMapperExt.selectByPrimaryKey(company.getItemId());
                if (Objects.isNull(article)) {
                    return null;
                }
                ArticleType type = articleTypeService.get(article.getTypeId());
                company.setArticle(FollowResponse.Article.builder()
                        .articleId(article.getId())
                        .title(article.getTitle())
                        .type(type.getName())
                        .build());
            } else if (company.getType() == 3 && openLive) {
                ResultModel<LiveInfoResponse> infoResponseResultModel = liveFeign.info(LiveInfoRequest.builder()
                        .roomId(company.getItemId())
                        .build());
                AssertUtil.isTrue(infoResponseResultModel);
                LiveInfoResponse infoResponse = infoResponseResultModel.getData();
                if (!infoResponse.isHasRoom()) {
                    return null;
                }
                company.setLive(FollowResponse.Live.builder()
                        .roomId(infoResponse.getRoomId())
                        .photo(infoResponse.getPhoto())
                        .title(infoResponse.getName())
                        .build());
            } else if (company.getType() == 4) {
                List<Integer> goodsIds = goodsApiCrmAppMapper.selectFollowGoods(company.getCompanyId());
                company.setGoods(ConvertUtils.list(goodsIds, goodsId -> {
                    return FollowResponse.Goods.builder()
                            .goodsId(goodsId)
                            .photo(OneStringUtils.photoResize(goodsPhotoService.getPath(goodsId)))
                            .build();
                }));
            }

            return company;
        });

        FollowResponse response = FollowResponse.builder()
                .companyPage(companyPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "1列表-关注用户")
    @GetMapping("user")
    @SecurityAuthCheck
    public ResultModel<FollowUserResponse> user(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        if (request.getPageNum() == 1) {
            userFeign.viewSave(UserViewSaveDto.builder().userId(optUser.getUserId()).type(UserApi.VIEW_TYPE_FOLLOW).build());
        }

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<FollowUserResponse.Content> contentList = userApiCrmAppMapper.selectPersonal(optUser.getUserId(), RecordPublicService.ITEMTYPE_USER, null);
        PageResponse2<FollowUserResponse.Content> contentPageResponse2 = ConvertUtils.page2(contentList, content -> {

            UserDto user = userAdminService.get(content.getUserId());
            content.setUserImg(user.getUserImg());
            content.setUserName(user.getName());
            BusinessCard card = businessCardBaseService.getByUserId(content.getUserId());
            if (Objects.nonNull(card)) {
                content.setPosition(card.getPosition());
                Company2Dto company = companyBaseService.get2(card.getCompanyId());
                boolean hasZkgx = companyBaseService.hasZkgx(content.getCompanyId());
                content.setCompanyId(company.getCompanyId());
                content.setCompanyName(company.getCompanyName());
                content.setCompanyLevel(company.countCompanyLevelView());
                content.setHasZkgx(BooleanUtils.toInteger(hasZkgx));
            }

            if (content.getType() == 1) {
                ResultModel<LiveInfoResponse> infoResponseResultModel = liveFeign.info(LiveInfoRequest.builder()
                        .roomId(content.getItemId())
                        .build());
                AssertUtil.isTrue(infoResponseResultModel);
                LiveInfoResponse infoResponse = infoResponseResultModel.getData();
                if (!infoResponse.isHasRoom()) {
                    return null;
                }
                if (infoResponse.getLiveStatus() == 2) {
                    content.setType(3);
                    content.setVideo(FollowUserResponse.Video.builder()
                            .roomId(infoResponse.getRoomId())
                            .name(infoResponse.getName())
                            .photo(infoResponse.getPhoto())
                            .videoUrl(infoResponse.getVideoUrl())
                            .userCurrentRoomId(infoResponse.getUserCurrentRoomId())

                            .cardId(card.getCardId())
                            .cardImg(card.getLogo())
                            .cardName(card.getName())
                            .userId(card.getUserId())
                            .userCollectFlag(BooleanUtils.toInteger(recordPublicService.isCollection(optUser.getUserId(), RecordPublicService.ITEMTYPE_USER, card.getUserId())))

                            .viewNum(recordPublicService.getPopularity(SeeRecordEnums.LIVE.getCode(), infoResponse.getRoomId()))
                            .collectNum(recordPublicService.getCollectionCount(RecordPublicService.ITEMTYPE_LIVE_ROOM, infoResponse.getRoomId()))
                            .collectFlag(BooleanUtils.toInteger(recordPublicService.isCollection(optUser.getUserId(), RecordPublicService.ITEMTYPE_LIVE_ROOM, infoResponse.getRoomId())))
                            .commentNum(recordPublicService.countCommentByType(DynamicApi.COMMENT_TYPE_VIDEO, infoResponse.getRoomId()))
                            .build());
                } else {
                    content.setLive(FollowUserResponse.Live.builder()
                            .roomId(infoResponse.getRoomId())
                            .photo(infoResponse.getPhoto())
                            .title(infoResponse.getName())
                            .status(LabelUtil.getLiveStatus(infoResponse.getLiveStatus()))
                            .build());
                }
            } else if (content.getType() == 2) {
                Dynamic dynamic = dynamicMapperExt.selectByPrimaryKey(content.getItemId());
                if (Objects.isNull(dynamic)) {
                    return null;
                }
                content.setDynamic(FollowUserResponse.Dynamic.builder()
                        .dynamicId(dynamic.getDynamicId())
                        .photos(dynamic.getPhotos())
                        .title(dynamic.getTitle())
                        .type(dynamic.getType())
                        .build());
            } else if (content.getType() == 4) {
                List<Integer> goodsIds = goodsApiCrmAppMapper.selectFollowGoods(content.getCompanyId());
                content.setGoods(ConvertUtils.list(goodsIds, goodsId -> {
                    return FollowUserResponse.Goods.builder()
                            .goodsId(goodsId)
                            .photo(OneStringUtils.photoResize(goodsPhotoService.getPath(goodsId)))
                            .build();
                }));
            }

            return content;
        });
        FollowUserResponse response = FollowUserResponse.builder()
                .contentPage(contentPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "2数字角标")
    @GetMapping("count")
    public ResultModel<FollowCountResponse> count() {
        final RequestContext requestContext = RequestContextHolder.getRequestContext();
        if (!requestContext.isLogin()) {
            FollowCountResponse response = FollowCountResponse.builder()
                    .unreadFollowNum(0L)
                    .unreadLiveNum(0L)
                    .unreadDynamicNum(0L)
                    .unreadLeadNum(0L)
                    .build();
            return ResultModel.success(response);
        }

        //获取最新浏览时间
        ResultModel<UserViewVo> userViewModel = userFeign.view(UserViewDto.builder().userId(requestContext.getUser().getUserId()).types(Lists.newArrayList(UserApi.VIEW_TYPE_FOLLOW, UserApi.VIEW_TYPE_LIVE, UserApi.VIEW_TYPE_DYNAMIC, UserApi.VIEW_TYPE_LEAD)).build());
        AssertUtil.isTrue(userViewModel);
        Map<Integer, Date> viewMap = userViewModel.getData().getViewMap();

        //未读关注
        PageHelper.startPage(1, 1);
        List<FollowUserResponse.Content> companyListCount = userApiCrmAppMapper.selectPersonal(requestContext.getUser().getUserId(), RecordPublicService.ITEMTYPE_USER, viewMap.get(UserApi.VIEW_TYPE_FOLLOW));
        Long unreadFollowNum = ((Page) companyListCount).getTotal();

        //未读直播短视频
        LiveListRequest liveListRequest = LiveListRequest.builder()
                .viewDate(viewMap.get(UserApi.VIEW_TYPE_LIVE))
                .build();
        liveListRequest.setPageNum(1);
        liveListRequest.setPageSize(1);
        ResultModel<LiveListVo> liveListVoResultModel = liveFeign.list(liveListRequest);
        AssertUtil.isTrue(liveListVoResultModel);
        Long unreadLiveNum = liveListVoResultModel.getData().getLivePage().getTotal();

        //未读红木圈
        DynamicListDto dynamicListDto = DynamicListDto.builder()
                .viewDate(viewMap.get(UserApi.VIEW_TYPE_DYNAMIC))
                .build();
        dynamicListDto.setPageNum(1);
        dynamicListDto.setPageSize(1);
        ResultModel<DynamicListVo> resultModel = dynamicFeign.list(dynamicListDto);
        AssertUtil.isTrue(resultModel);
        Long unreadDynamicNum = resultModel.getData().getDynamics().getTotal();

        //未读头条
        final Integer companyId = requestContext.isCard() ? requestContext.getUser().getCompanyId() : ArticleApi.DEFAULT_COMPANYID;
        String excludeLabelIds = null;
        if (requestContext.isLogin() && !requestContext.isCard()) {
            Integer supplierLabelId = companyBaseService.getLabelId(CompanyBaseService.LABEL_SUPPLIER);
            Integer jxsLabelId = companyBaseService.getLabelId(CompanyBaseService.LABEL_JXS);
            excludeLabelIds = SqlUtil.in(Lists.newArrayList(String.valueOf(supplierLabelId), String.valueOf(jxsLabelId)));
        }
        PageHelper.startPage(1, 1);
        List<Article> articleList = articleApiCrmAppMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, ArticleApi.POSITION_TOP, null, excludeLabelIds, viewMap.get(UserApi.VIEW_TYPE_LEAD), null);
        Long unreadLeadNum = ((Page) articleList).getTotal();

        FollowCountResponse response = FollowCountResponse.builder()
                .unreadFollowNum(unreadFollowNum)
                .unreadLiveNum(unreadLiveNum)
                .unreadDynamicNum(unreadDynamicNum)
                .unreadLeadNum(unreadLeadNum)
                .build();
        return ResultModel.success(response);
    }
}
